//
//  BMHFeedbackController.m
//  BMHVideoMain
//
//  Created by 陈宪栋 on 2017/4/6.
//  Copyright © 2017年 Baomihua. All rights reserved.
//

#import "BMHFeedbackController.h"
#import <UtilsMacro.h>
//#import "BMHAPIManager.h"
#import <Masonry.h>
#import <ReactiveCocoa.h>
#import "XLHTTPSessionManager.h"
#import "XLAccountManager.h"
#import "XLUserInfoModel.h"

@interface BMHFeedbackController ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>
@property (nonatomic, strong) UITableView *feedbackTableview;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UILabel *QQLabel;
@property (nonatomic, strong) UILabel *QQLabel2;
@property (nonatomic, strong) UIView *BGView;
@property (nonatomic, strong) UILabel *numLabel;
@property (nonatomic, strong) NSString *QQnumber;
@property (nonatomic, strong) UITextView *textView;
@end

@implementation BMHFeedbackController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self remove];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //self.currentPageId = @"feedback";
    [self showBackButton:NULL];
    _QQnumber = @"";
    self.navigationItem.title = @"意见反馈";
    [self getQQnumber];
    [self setupView];
}
- (void)getQQnumber{
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/Api/v2/UserInfo/GetQQ" parameters:nil resultClass:nil]subscribeNext:^(id x) {
        _QQnumber = x;
    } error:^(NSError *error) {
        
    }];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //[BMHStatisticsTool beginLogPageView:@"意见反馈页面"];
//    [_textView becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //[BMHStatisticsTool endLogPageView:@"意见反馈页面"];
}

- (void)setupView {
    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat height = CGRectGetHeight(self.view.frame);
    UITableView *tableView = [[UITableView alloc] initWithFrame:(CGRect){CGPointZero, width, height} style:UITableViewStyleGrouped];
    [self.view addSubview:tableView];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.backgroundView = nil;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.sectionFooterHeight = 0.0;
    tableView.allowsSelection = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _feedbackTableview = tableView;
    
    // textView
    UITextView *textView = [[UITextView alloc] init];
    textView.font = [UIFont systemFontOfSize:16];
    textView.backgroundColor = XLThemeColor;
    textView.layer.masksToBounds = YES;
    textView.layer.cornerRadius = 2.0f;
    textView.layer.borderColor = kLightGrayColor.CGColor;
    textView.layer.borderWidth = 0.5f;
    textView.delegate = self;
    textView.textColor = [UIColor darkGrayColor];
    textView.frame = (CGRect){10, 0, SCREEN_WIDTH - 20, 120};
    _textView = textView;
    
    // tipLabel
    UILabel *tipLabel = [[UILabel alloc] init];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.textColor = [UIColor lightGrayColor];
    tipLabel.font = [UIFont systemFontOfSize:13];
    tipLabel.text = @"   您的反馈和建议一经采纳，会给予您1000金豆奖励";
    _tipLabel = tipLabel;
    
    // qqlabel
    UILabel *qqLabel = [[UILabel alloc] init];
    qqLabel.backgroundColor = [UIColor clearColor];
    qqLabel.textColor = [UIColor lightGrayColor];
    qqLabel.font = [UIFont systemFontOfSize:13];
    qqLabel.text = @"   您可以直接加入QQ群反馈意见";
    _QQLabel = qqLabel;
    // qqlabel2
    UILabel *qqLabel2 = [[UILabel alloc] init];
    qqLabel2.backgroundColor = [UIColor clearColor];
    qqLabel2.textColor = [UIColor blackColor];qqLabel2.userInteractionEnabled = YES;
    qqLabel2.font = [UIFont systemFontOfSize:16];
    qqLabel2.frame = (CGRect){10, 0, SCREEN_WIDTH - 20, 44};
    qqLabel2.text = @"复制群号并打开QQ";
    _QQLabel2 = qqLabel2;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(joinQQGroup)];
    [qqLabel2 addGestureRecognizer:tap];
    
    // numLabel
    UILabel *numLabel = [[UILabel alloc] init];
    numLabel.backgroundColor = [UIColor clearColor];
    numLabel.textColor = [UIColor lightGrayColor];
    numLabel.font = [UIFont systemFontOfSize:14];
    numLabel.text = @"   还可以输入200字";
    _numLabel = numLabel;
    
    UIImageView *joinQQGroup = [[UIImageView alloc]init];
    joinQQGroup.frame = CGRectMake(qqLabel2.frame.size.width - 60, 6, 32, 32);
    [joinQQGroup setImage:[UIImage imageNamed:@"图标_logo_QQ"]];
    [_QQLabel2 addSubview:joinQQGroup];
    UIImageView *joinQQGroup2 = [[UIImageView alloc]init];
    joinQQGroup2.frame = CGRectMake(qqLabel2.frame.size.width - 24, 10, 24, 24);
    [joinQQGroup2 setImage:[UIImage imageNamed:@"common_icon_jinru_n"]];
    [_QQLabel2 addSubview:joinQQGroup2];

    _BGView = [[UIView alloc]initWithFrame:self.view.frame];
    _BGView.backgroundColor = kClearColor;
    
    UIView *BGView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    BGView2.backgroundColor = RGBA_HEX(0x000000, 0.3);
    [_BGView addSubview:BGView2];
    UIView *centerView= [[UIView alloc]init];
    centerView.layer.cornerRadius = 5;
    centerView.frame = CGRectMake(ScreenWidth/2 -140, ScreenHeight/2-100, 280, 200);
    [BGView2 addSubview:centerView];
    UILabel *texLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 60, 180, 60)];
    texLabel.textColor = [UIColor lightGrayColor];
    texLabel.font = [UIFont systemFontOfSize:15];
    texLabel.text = @"官方QQ群号已复制成功是否马上加入？";
    texLabel.numberOfLines = 0;
    [centerView addSubview:texLabel];
    UILabel *texLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 180, 60)];
    texLabel2.textColor = [UIColor blackColor];
    texLabel2.font = [UIFont systemFontOfSize:18];
    texLabel2.text = @"加入QQ群";
    [centerView addSubview:texLabel2];
    centerView.backgroundColor = kWhiteColor;
    texLabel.textAlignment = texLabel2.textAlignment = NSTextAlignmentCenter;
    UIButton *Xbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    Xbutton.frame = CGRectMake(230, 10, 40, 40);
    [Xbutton setImage:[UIImage imageNamed:@"common_but_chacha_n"] forState:UIControlStateNormal];
    [Xbutton addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside];
    [centerView addSubview:Xbutton];
    UIButton *joinbutton = [UIButton buttonWithType:UIButtonTypeCustom];
    joinbutton.frame = CGRectMake(15, 142, 250, 44);
    joinbutton.layer.cornerRadius = 5;joinbutton.backgroundColor = RGB_HEX(0xffbb01);
    [joinbutton setTitle:@"打开QQ" forState:UIControlStateNormal];
    [joinbutton addTarget:self action:@selector(joinGroup) forControlEvents:UIControlEventTouchUpInside];
    [centerView addSubview:joinbutton];
}
- (void)remove{
    [_BGView removeFromSuperview];
}
- (void)joinQQGroup{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = _QQnumber;
    UIWindow * windows = [UIApplication sharedApplication].keyWindow;
    [windows addSubview:_BGView];
}

- (BOOL)joinGroup{
    [_BGView removeFromSuperview];
    NSString *urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&uin=%@&key=%@&card_type=group&source=external", _QQnumber,@"6f84c5915b6f0e0a45cbeab967e3a4fd13fb4cad3d9ec2b1a5bac2c6be04553d"];
    NSURL *url = [NSURL URLWithString:urlStr];
    if([[UIApplication sharedApplication] canOpenURL:url]){
        [[UIApplication sharedApplication] openURL:url];
        return YES;
    }
    else return NO;
}
#pragma mark - UITextView Delegate
- (void)textViewDidChange:(UITextView *)textView
{
    NSUInteger count = _textView.text.length;
    NSString *title = [NSString stringWithFormat:@"   还可以输入%@字", @(200 - count)];
    if (count > 200) {
        title = [NSString stringWithFormat:@"   超出%@字", @(count - 200)];
        _numLabel.textColor = [UIColor redColor];
    }
    else {
        _numLabel.textColor = [UIColor lightGrayColor];
    }
    _numLabel.text = title;
}

- (void)subClicked
{
    NSString *content = _textView.text;
    if (content.length > 200) {
        NSString *title = [_numLabel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if ([content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入内容" message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else { // 提交反馈信息
        [_textView resignFirstResponder];
        [MBProgressHUD showMessage:@"" toView:self.view];
        @weakify(self);
        
        
        [[[XLHTTPSessionManager sharedManager]XLV2POST:@"api/v1/advise/submit" parameters:@{@"UserId":SafeStr([[XLAccountManager shareInstance] model].Id),@"Content":SafeStr(content)} resultClass:nil] subscribeNext:^(id x) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showContent:@"提交成功" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        } error:^(NSError *error) {
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey] toView:self.view];
        }];
        
//        [[[XLHTTPSessionManager sharedBMHManager] feedbackWithUserId:[[XLAccountManager shareInstance] model].Id content:content] subscribeNext:^(id x) {
//            @strongify(self);
//            [MBProgressHUD hideHUDForView:self.view];
//            [MBProgressHUD showContent:@"提交成功" toView:self.view];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//        } error:^(NSError *error) {
//            @strongify(self);
//            [MBProgressHUD hideHUDForView:self.view];
//            [MBProgressHUD showError:error.userInfo[NSLocalizedDescriptionKey] toView:self.view];
//        }];

    }
}

#pragma mark - UITableview Delegate & Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        static NSString *cellIdentifier = @"qqCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.backgroundColor = [UIColor clearColor];
            cell.backgroundView = nil;
            [cell.contentView addSubview:_QQLabel2];
        }
        return cell;
    }
    if (section == 1) {
        static NSString *cellIdentifier = @"textCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.backgroundColor = [UIColor clearColor];
            cell.backgroundView = nil;
            [cell.contentView addSubview:_textView];
        }
        return cell;
    }
    
    static NSString *cellIdentifier = @"btnCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.backgroundView = nil;
        
        // 提交按钮
        UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [subBtn setTitle:@"提 交" forState:UIControlStateNormal];
        [subBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [subBtn setBackgroundColor:RGB_HEX(0xffbb01)];
        [cell.contentView addSubview:subBtn];
        subBtn.layer.masksToBounds = YES;
        subBtn.layer.cornerRadius = 2.0f;
        subBtn.frame = (CGRect){10, 0, SCREEN_WIDTH - 20, 44};
        [subBtn addTarget:self action:@selector(subClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    return section == 1? 120 : 40;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return _QQLabel;
    }
    if (section == 1) {
        return _tipLabel;
    }
    return nil;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
    }
}
@end
